<?php
namespace Kuoqi\Spider;
use Kuoqi\Curl;
use Kuoqi\Cache;
class Chrome{
	
	
	public $proxy = null;//代理模块
	
	public $target = '';//目标地址
	
	public $cacheTime = 0;//同时间内，会自动从缓存中获取页面信息，二并不会去完全拿取，减少服务端压力
	
	private $objCache = null;//cache对象
	
	public function __construct(){
		$this->proxy = 	new Curl();
	}
	
	//配置缓存相关信息，
	
	//蜘蛛爬到一个页面
	public function to($url){
		$this->target = $url;
		if($proxy = Cache::getCache($url,'/collect',false)){
			//这里做一点东西，证明这个是可以使用的
			$this->proxy = $proxy;
		}else{
			$this->doTry();
		}
		return $this;
	}
	
	public function cache($timer){
		$this->cacheTime = $timer;	
	}
	
	//尝试获取到显示的流
	public function stream(){
		return $this->proxy->response->response;
	}
	
	//尝试执行
	//如果执行失败的话，可以尝试手动执行的喔
	public function doTry(){
		$this->proxy->curl = $this->target;//配置目标地址
		//配置请求头
		//尝试获取当前的信息，如果失败则使用默认
		if(isset($_SERVER['HTTP_USER_AGENT'])){
			$this->proxy->useagent = $_SERVER['HTTP_USER_AGENT'];
		}else{
			$this->proxy->useagent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36';	
		}
		//配置常规的请求头信息
		$this->proxy->headinfo = array('Content-Type:text/html;CHARSET=utf-8');
		
		//配置cookie
		if(isset($GLOBALS['_COOKIE'])){
			$cookie = array();
			foreach($GLOBALS['_COOKIE'] as $k=>$v){
				$cookie[] = $k.'='.$v;	
			}	
		}
		$this->proxy->cookie = implode('; ',$cookie);
		$this->proxy->request();
		Cache::setCache($this->target,$this->proxy,$this->cacheTime,'/collect',false);
		return $this;	
	}
	
}